package com.tag.socialhub.facebook;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.code.facebookapi.FacebookJsonRestClient;

public class FB extends HttpServlet {
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String apiKey = getServletConfig().getInitParameter("API_KEY");
		String secretKey = getServletConfig().getInitParameter("SECRET_KEY");
		HttpSession session = request.getSession();
		String sessionKey = (String) session
				.getAttribute("restSearchAppSession");
		String authToken = request.getParameter("auth_token");

		FacebookJsonRestClient client = null;

		if (sessionKey != null) {
			client = new FacebookJsonRestClient(apiKey, secretKey, sessionKey);

		} else if (authToken != null) {
			client = new FacebookJsonRestClient(apiKey, secretKey);
			// client. isDesktop(false);
			try {
				sessionKey = client.auth_getSession(authToken);
				session.setAttribute("restSearchAppSession", sessionKey);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			response
					.sendRedirect("http://www.facebook.com/login.php?return_session=true&session_key_only=true&api_key="
							+ apiKey);
			return;
		}
		// response.getWriter().println("HelloWorld");
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		String title = "Reading All Request Parameters";
		out.println("<head><title>" + title + "</title></head>"
				+ "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title
				+ "</H1>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n"
				+ "<TR BGCOLOR=\"#FFAD00\">\n"
				+ "<TH>Parameter Name<TH>Parameter Value(s)");
		Enumeration paramNames = request.getParameterNames();
		while (paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			out.println("<TR><TD>" + paramName + "\n<TD>");
			String[] paramValues = request.getParameterValues(paramName);
			if (paramValues.length == 1) {
				String paramValue = paramValues[0];
				if (paramValue.length() == 0)
					out.print("<I>No Value</I>");
				else
					out.print(paramValue);
			} else {
				out.println("<UL>");
				for (int i = 0; i < paramValues.length; i++) {
					out.println("<LI>" + paramValues[i]);
				}
				out.println("</UL>");
			}
		}
		out.println("</TABLE>\n");
		StringBuffer url = new StringBuffer();
		url.append("https://graph.facebook.com/oauth/authorize?client_id=");
		url.append(apiKey);
		url
				.append("&redirect_uri=http://tgreening.appspot.com/oauth_redirect\"");
		out.println("<a href=\"" + url.toString() + "\"> Get code </a>");
		out.println("</BODY></HTML>");

	}
}
